# coding: utf-8
import os
import requests
import json

import sys


class XiechengSpider(object):
    def __init__(self):
        self.t = ('shanghai', 'nanjing', '上海', '南京', '2017-11-25', '2017-11-25')
        self.url = 'http://trains.ctrip.com/TrainBooking/Ajax/SearchListHandler.ashx?Action=getSearchList'
        _data = '{{"IsBus":false,"Filter":"0","Catalog":"","IsGaoTie":false,"IsDongChe":false,"CatalogName":"","DepartureCity":"{0}","ArrivalCity":"{1}","HubCity":"","DepartureCityName":"{2}","ArrivalCityName":"{3}","DepartureDate":"{4}","DepartureDateReturn":"{5}","ArrivalDate":"","TrainNumber":""}}'.format(
            *self.t)
        # self.con = '{"IsBus":false,"Filter":"0","Catalog":"","IsGaoTie":false,"IsDongChe":false,"CatalogName":"","DepartureCity":"shanghai","ArrivalCity":"nanjing","HubCity":"","DepartureCityName":"上海","ArrivalCityName":"南京","DepartureDate":"2017-11-25","DepartureDateReturn":"2017-11-25","ArrivalDate":"","TrainNumber":""}'
        self.data = {'value': _data}
        self.filename = 'ext/E3_xiecheng_train.json'

        _path = os.path.join(os.path.abspath('.'), '../')
        sys.path.append(_path)
        self.ei = __import__('Utils.C002_extract_info', fromlist=['C002_extract_info'])
        self.ua_file = {'pc': '{0}Utils/{1}'.format(_path, self.ei.ExtractInfo.ua_file['pc'])}
        self.user_agent = self.ei.ExtractInfo.get_useragent(file=self.ua_file)

    def run(self):
        _response = requests.post(url=self.url, data=self.data, headers=self.user_agent)
        with open(self.filename, 'w', encoding='utf-8', errors='ignore') as f:
            f.write(_response.content.decode(encoding='gb18030'))


def main():
    xc = XiechengSpider()
    xc.run()


if __name__ == '__main__':
    main()
